package com.juyu.miliao.api.yidun.util;

import com.juyu.miliao.api.yidun.constant.AntispamConstant;
import com.juyu.miliao.common.util.UUIDUtil;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author jh
 * 14:34
 */
public class YidunUtil {

	/**
	 * 易盾-反垃圾
	 * 生成签名信息
	 *
	 * @param secretKey 产品私钥
	 * @param params    接口请求参数名和参数值map，不包括signature参数名
	 * @return Signature
	 */
	public static String genSignature(String secretKey, Map<String, String> params) {
		// 1. 参数名按照ASCII码表升序排序
		String[] keys = params.keySet().toArray(new String[0]);
		Arrays.sort(keys);

		// 2. 按照排序拼接参数名与参数值
		StringBuilder sb = new StringBuilder();
		for (String key : keys) {
			sb.append(key).append(params.get(key));
		}
		// 3. 将secretKey拼接到最后
		sb.append(secretKey);

		// 4. MD5是128位长度的摘要算法，转换为十六进制之后长度为32字符
		String signature = null;
		try {
			signature = DigestUtils.md5Hex(sb.toString().getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return signature;
	}

	/**
	 * 返回连接易盾公共参数
	 *
	 * @return map
	 */
	public static Map<String, String> getCommonParamMap() {
		Map<String, String> map = new HashMap<>(16);

		// 1.设置公共参数
		map.put("secretId", AntispamConstant.SECRETID);
		map.put("businessId", AntispamConstant.BUSINESSID);
		map.put("version", "v3.1");
		map.put("timestamp", String.valueOf(System.currentTimeMillis()));
		map.put("nonce", String.valueOf(new Random().nextInt()));

		//2.设置私有参数
		map.put("dataId", UUIDUtil.getUUID());

		return map;
	}

}
